<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <!--用户数据-->
      <el-col :span="24" :xs="24" class="div-height-left">
        <div class="search-container">
          <el-form
            v-show="showSearch"
            ref="queryParamsRef"
            :inline="true"
            :model="queryParams"
            label-width="80px"
          >
            <el-form-item v-if="!userInfo.orgId" label="机构">
              <select-org-tree
                :value="queryParams.orgId"
                class="width-120"
                @getTreeSelect="getTreeSelect"
                @orgNodeClick="orgNodeClick"
              />
            </el-form-item>
            <el-form-item label="登录名称" prop="userName">
              <el-input
                v-model="queryParams.userName"
                clearable
                placeholder="请输入登录名称"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                clearable
                placeholder="请输入手机号码"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <el-radio-group v-model="queryParams.status" @change="handleQuery">
                <el-radio value="">全部</el-radio>
                <el-radio
                  v-for="dict in dictDataMap['sys_normal_disable']"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                :unlink-panels="true"
                end-placeholder="结束日期"
                range-separator="截止"
                start-placeholder="开始日期"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </el-form-item>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8" style="margin-right: 300px">
          <el-col :span="1.5">
            <el-button
              v-hasPerm="['system:user:add']"
              plain
              type="primary"
              @click="handleAdd"
            >
              <template #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPerm="['system:user:import']"
              plain
              type="info"
              @click="handleImport"
            >
              <template #icon>
                <i-ep-upload/>
              </template>
              导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-tooltip
              class="item"
              content="如果只需要导出单个机构的数据，请选择对应机构点击，如果需要导出所有数据，请清除机构选项点击"
              effect="dark"
              placement="right"
            >
              <el-button
                v-hasPerm="['system:user:export']"
                plain
                type="warning"
                @click="handleExport"
              >
                <template #icon>
                  <i-ep-download/>
                </template>
                导出
              </el-button>
            </el-tooltip>
          </el-col>
          <el-col :span="1.5">
            <el-button plain type="danger" @click="refreshCacheUserFun"
            >
              <template #icon>
                <i-ep-refresh/>
              </template>
              刷新缓存
            </el-button>
          </el-col>
        </el-row>
        <!-- <el-row>
        </el-row> -->
        <el-row :gutter="10" class="div-height-left">
          <el-col :span="4" style="height: calc(100% - 62px)">
            <!--部门树-->
            <dept-tree
              :height="'calc(100% - 50px)'"
              :orgId="queryParams.orgId"
              @treeClick="treeClick"
            />
          </el-col>
          <el-col :span="20" :xs="24">
            <el-table
              ref="tableRef"
              v-adaptive
              :border="true"
              :data="userList"
              :header-cell-style="$headerCellStyle"
              :stripe="true"
              highlight-current-row
            >
              <el-table-column
                :header-align="'center'"
                :show-overflow-tooltip="true"
                label="所属机构"
                min-width="70px"
                prop="orgName"
              />
              <el-table-column
                :align="'left'"
                :show-overflow-tooltip="true"
                label="岗位"
                min-width="120px"
                prop="userPostArray"
              >
                <template #default="scope">
                  <dict-data-tag :options="dictDataMap['user_post_dict']"
                                 :value="scope.row.userPost ? scope.row.userPost.split(',') : []"/>
                </template>
              </el-table-column>
              <el-table-column
                v-if="columns[0].visible"
                key="userId"
                :header-align="'center'"
                :show-overflow-tooltip="true"
                label="用户编号"
                prop="userId"
                width="130"
              />
              <el-table-column
                v-if="columns[1].visible"
                key="userName"
                :header-align="'center'"
                :show-overflow-tooltip="true"
                label="登录名称"
                prop="userName"
                width="100"
              />
              <el-table-column
                v-if="columns[2].visible"
                key="nickName"
                :header-align="'center'"
                :show-overflow-tooltip="true"
                label="用户昵称"
                prop="nickName"
              />
              <el-table-column
                key="professionalTitleName"
                :header-align="'center'"
                :show-overflow-tooltip="true"
                label="职称"
                prop="professionalTitleName"
                width="100"
              />
              <el-table-column
                v-if="columns[3].visible"
                key="deptName"
                :header-align="'center'"
                :show-overflow-tooltip="true"
                label="部门"
                prop="dept.deptName"
                width="90"
              />
              <el-table-column
                key="medicalCode"
                :header-align="'center'"
                :show-overflow-tooltip="true"
                label="医保代码"
                prop="medicalCode"
                width="220"
              />
              <el-table-column
                v-if="columns[4].visible"
                key="phonenumber"
                :align="'center'"
                label="手机号码"
                prop="phonenumber"
                width="120"
              />
              <el-table-column
                v-if="columns[5].visible"
                key="status"
                :align="'center'"
                label="状态"
                width="80"
              >
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.status"
                    active-value="0"
                    inactive-value="1"
                    @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column
                v-if="columns[6].visible"
                :align="'center'"
                label="创建时间"
                prop="createTime"
                width="160"
              >
                <template #default="scope">
                  <span>{{ $parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :align="'center'"
                class-name="small-padding fixed-width"
                label="操作"
                width="220"
              >
                <template #default="scope">
                  <div v-if="scope.row.userId !== 1">
                    <el-button
                      v-hasPerm="['system:user:edit']"
                      type="primary"
                      @click="handleUpdate(scope.row)"
                    >
                      <template #icon>
                        <i-ep-edit/>
                      </template>
                      修改
                    </el-button>
                    <el-button
                      v-hasPerm="['system:user:remove']"
                      type="danger"
                      @click="handleDelete(scope.row)"
                    >
                      <template #icon>
                        <i-ep-delete/>
                      </template>
                      删除
                    </el-button>
                    <el-dropdown
                      v-hasPerm="['system:user:resetPwd', 'system:user:edit']"
                      @command="(command) => handleCommand(command, scope.row)"
                    >
                      <span class="el-dropdown-link" style="margin-top: 7px">
                        <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu v-hasPerm="['system:user:resetPwd']">
                          <el-dropdown-item command="handleResetPwd"
                          >重置密码
                          </el-dropdown-item>
                          <!-- <el-dropdown-item v-hasPerm="['system:user:edit']"
                              command="handleAuthRole">
                              <template #icon><i-ep-check />
                              </template>分配角色
          </el-dropdown-item> -->
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-if="total > 0"
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.pageNum"
              :total="total"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="title"
      append-to-body
      width="800px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="40">
          <el-col v-if="!userInfo.orgId" :span="24">
            <el-form-item label="所属机构" prop="orgId">
              <select-org-tree
                v-model="form.orgId"
                :value="form.orgId"
                style="width: 100%"
                @getTreeSelect="getTreeSelect"
                @orgNodeClick="dialogOrgTree"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="form.nickName"
                maxlength="30"
                placeholder="请输入用户昵称"
                @blur="nickNameBlueFun"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属科室" prop="deptId">
              <base-dept-tree
                :org-id="form.orgId"
                :value="form.deptId"
                style="width: 100%"
                @deptSelect="deptSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色类型" prop="customerType">
              <el-select
                v-model="form.customerType"
                clearable
                placeholder="请选择用户角色类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dictDataMap['user_customer_type']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="userPostArray">
              <el-select
                v-model="form.userPostArray"
                clearable multiple
                placeholder="请选择用户岗位"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dictDataMap['user_post_dict']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="professionalTitle">
              <el-select
                v-model="form.professionalTitle"
                clearable
                placeholder="请选择用户职称"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dictDataMap['professional_title_dict']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input
                v-model="form.phonenumber"
                maxlength="11"
                placeholder="请输入手机号码"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件类型" prop="certificateType">
              <el-select
                v-model="form.certificateType"
                clearable
                placeholder="请选择证件类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dictDataMap['certificate_type']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="certificateNo">
              <el-input
                v-model="form.certificateNo"
                placeholder="请输入证件号码"
                @blur="certificateNoBlur"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" maxlength="50" placeholder="请输入邮箱"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名称" prop="userName">
              <el-input
                v-model="form.userName"
                :readonly="form.userId == ''"
                maxlength="30"
                placeholder="请输入登录名称"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="!isPasswordReadonly" :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input
                v-model="form.password"
                auto-complete="off"
                maxlength="20"
                placeholder="请输入用户密码"
                show-password
                type="password"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
                <el-option
                  v-for="dict in dictDataMap['sys_user_sex']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dictDataMap['sys_normal_disable']"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医保代码" prop="medicalCode">
              <el-input v-model="form.medicalCode" placeholder="医保代码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                placeholder="请输入内容"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <!-- <el-dialog :title="upload.title" v-model="upload.open" append-to-body width="400px">
        <el-upload ref="upload" :action="upload.url + '?updateSupport=' + upload.updateSupport" :auto-upload="false"
            :disabled="upload.isUploading" :headers="upload.headers" :limit="1" :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess" accept=".xlsx, .xls" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip text-center">
                <div slot="tip" class="el-upload__tip">
                    <el-checkbox v-model="upload.updateSupport" />
                    是否更新已经存在的用户数据
                </div>
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary"
                    @click="importTemplate">下载模板
                </el-link>
            </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button   type="primary" @click="submitFileForm">确 定</el-button>
            <el-button   @click="upload.open = false">取 消</el-button>
        </div>
    </el-dialog> -->
  </div>
</template>

<script lang="ts" setup>
import {
  addUser,
  changeUserStatus,
  delUser,
  getUser,
  listUser,
  refreshCacheUser,
  resetUserPwd,
  updateUser,
} from "@/api/system/user";
import {listDept} from "@/api/system/dept";
import {getToken} from "@/utils/auth";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";
import {useRouter} from "vue-router";
import {firstLetterResult} from "@/utils/pinyin.ts";

const {proxy} = getCurrentInstance() as any;
const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
const router = useRouter();
const dictDataMap = ref(
  dictStore.isTypeGetData(
    "sys_normal_disable",
    "sys_user_sex",
    "user_customer_type",
    "certificate_type",
    "user_post_dict",
    "professional_title_dict"
  )
);

// table元素
const tableRef = ref();
// table高度
const tableHeight = ref();

onMounted(() => {
  // // 设置表格初始高度为innerHeight-offsetTop-表格底部与浏览器底部距离85
  // tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 300;
  // // 监听浏览器高度变化
  // window.onresize = () => {
  //     tableHeight.value = window.innerHeight - tableRef.value.$el.offsetTop - 300;
  // };
});
const formRef = ref();
const queryForm = ref();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref<boolean>(true);
// 非多个禁用
const multiple = ref<boolean>(true);
// 显示搜索条件
const showSearch = ref<boolean>(true);
// 总条数
const total = ref<number>(0);
// 用户表格数据
const userList = ref<any>(null);
// 弹出层标题
const title = ref<string>("");
// 部门树选项
const deptOptions = ref<any[]>([]);
// 是否显示弹出层
const open = ref<boolean>(false);
// 部门名称
const deptName = ref<string>("");
// 默认密码
const initPassword = ref<string>("");
// 日期范围
const dateRange = ref<any[]>([]);
// 岗位选项
const postOptions = ref<any[]>([]);
// 角色选项
const roleOptions = ref<any[]>([]);
const isPasswordReadonly = ref<boolean>(true);
// 查询参数
const queryParamsRef = ref();
const queryParams = ref<SysUser>({
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  phonenumber: undefined,
  status: "",
  deptId: undefined,
  orgId: "",
});
// 表单参数
const form = ref<SysUser>({
  userId: undefined,
  userPost: undefined,
  customerType: "3",
  professionalTitle: "1",
  certificateType: "0",
  certificateNo: "",
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  password: undefined,
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: "0",
  remark: undefined,
  postIds: [],
  roleIds: [],
  orgId: queryParams.value.orgId,
  nickNameBlue: undefined
});
const defaultProps = {
  children: "children",
  label: "label",
};

// 用户导入参数
const upload = {
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  // url: window.urlConfig.baseURL + "/system/user/importData"
};
// 列信息
const columns = [
  {key: 0, label: `用户编号`, visible: true},
  {key: 1, label: `登录名称`, visible: true},
  {key: 2, label: `用户昵称`, visible: true},
  {key: 3, label: `部门`, visible: true},
  {key: 4, label: `手机号码`, visible: true},
  {key: 5, label: `状态`, visible: true},
  {key: 6, label: `创建时间`, visible: true},
];
// 表单校验
const rules = ref({
  userName: [
    {required: true, message: "登录名称不能为空", trigger: "blur"},
    {min: 2, max: 20, message: "登录名称长度必须介于 2 和 20 之间", trigger: "blur"},
  ],
  nickName: [{required: true, message: "用户昵称不能为空", trigger: "blur"}],
  customerType: [{required: true, message: "用户角色类型不能为空", trigger: "change"}],
  deptId: [{required: true, message: "归属部门不能为空", trigger: "blur"}],
  password: [
    {required: true, message: "用户密码不能为空", trigger: "blur"},
    {min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur"},
  ],
  email: [
    {
      required: false,
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  userPostArray: [
    {
      required: "true",
      message: "请选择岗位信息",
      trigger: ["blur", "change"],
    },
  ],
  phonenumber: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

setOrgInfo();

function setOrgInfo() {
  if (userInfo.orgId) {
    queryParams.value.orgId = userInfo.orgId;
    getDeptTree();
    getList();
  } else {
    getTreeSelect("");
    queryParams.value.orgId = "";
  }
  proxy.$getConfigKey("sys.user.initPassword").then((response) => {
    initPassword.value = response.msg;
  });
}

// watch(deptName, (new, _old)=> {
//     $refs.tree.filter(new);
// })

/** 证件号码输入框焦点消失事件 */
function certificateNoBlur() {
  if (form.value.certificateType === "0") {
    form.value.sex = proxy.$certificateNoInSex(form.value.certificateNo);
  }
}

/** 查询机构下拉树结构 */
function getTreeSelect(response) {
  if (response) {
    // queryParams.value.orgId = response.data[0].orgId
    getDeptTree();
  }
}

/** 左侧部门树节点点击事件 */
function treeClick(obj) {
  queryParams.value.deptId = obj.id;
  getList();
}

/** 查询用户列表 */
function getList() {
  listUser(proxy.$addDateRange(queryParams.value, dateRange.value)).then(
    (response: any) => {
      userList.value = response.rows;
      total.value = response.total;
    }
  );
}

function deptSelect(node) {
  form.value.deptId = node.deptId;
  form.value.deptName = node.deptName;
}

/** 转换部门数据结构 */
function normalizer(node) {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.deptId,
    label: node.deptName,
    children: node.children,
  };
}

// 机构树点击事件
function orgNodeClick(data, _e) {
  queryParams.value.orgId = data.orgId;
  if (queryParams.value.orgId) {
    getDeptTree();
    getList();
  }
}

/** 维护弹出框机构树点击事件 */
function dialogOrgTree(data, _e) {
  form.value.orgId = data.orgId;
}

/** 转换机构数据结构 */
function sysOrgNormalizer(node) {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.orgId,
    label: node.orgName,
    children: node.children,
  };
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  listDept({delFlag: "0", status: "0", orgId: queryParams.value.orgId}).then(
    (response) => {
      if (form.value.deptId) {
        let index = Array.from(response.data).findIndex((item: any) => {
          return (item.deptId = form.value.deptId);
        });
        if (index == -1) {
          form.value.deptId = undefined;
        }
      }
      deptOptions.value = proxy.$handleTree(response.data, "deptId", "deptName");
    }
  );
}

// 筛选节点
function filterNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

// 节点单击事件
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
}

// 用户状态修改
function handleStatusChange(row: any) {
  let text = row.status === "0" ? "启用" : "停用";
  ElMessageBox.confirm('确认要"' + text + '""' + row.nickName + '"用户吗？', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      changeUserStatus(row.userId, row.status).then(() => {
        ElMessage.success(text + "成功");
      });
    })
    .catch(() => {
      row.status = row.status === "0" ? "1" : "0";
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    userId: undefined,
    customerType: "3",
    professionalTitle: "1",
    certificateType: "0",
    certificateNo: "",
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: [],
    orgId: queryParams.value.orgId,
  };
  // proxy.$resetForm(form)
  if (userInfo.orgId === "1") {
    getTreeSelect("");
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择所属机构后添加");
  }
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = "";
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  dateRange.value = [];
  queryParams.value.userName = "";
  queryParams.value.phonenumber = "";
  // getLoginUser();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 更多操作触发
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row);
      break;
    case "handleAuthRole":
      handleAuthRole(row);
      break;
    default:
      break;
  }
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择所属机构后添加");
  }
  reset();
  getUser("").then((response) => {
    postOptions.value = response.data.posts;
    roleOptions.value = response.data.roles;
    open.value = true;
    title.value = "添加用户";
    form.value.password = initPassword.value;
    isPasswordReadonly.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  queryParams.value.orgId = row.orgId;
  getDeptTree();
  const userId = row.userId || ids.value;
  getUser(userId).then((response) => {
    form.value = response.data.user;
    postOptions.value = response.data.posts;
    roleOptions.value = response.data.roles;
    form.value.postIds = response.data.postIds;
    form.value.roleIds = response.data.roleIds;
    open.value = true;
    title.value = "修改用户";
    isPasswordReadonly.value = true;
    // form.value.password = "";
  });
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  ElMessageBox.prompt('请输入"' + row.userName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
  })
    .then(({value}) => {
      resetUserPwd(row.userId, value).then((_response) => {
        ElMessage.success("修改成功，新密码是：" + value);
      });
    })
    .catch(() => {
    });
}

/** 分配角色操作 */
function handleAuthRole(row) {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    form.value.userType = "sys_user";
    if (userInfo.orgId) {
      form.value.orgId = userInfo.orgId;
    }
    if (valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then((_response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((_response) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value;
  ElMessageBox.confirm("是否删除选中的数据项？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delUser(userIds).then((_res) => {
        getList();
      });
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {
    });
}

/** 导出按钮操作 */
function handleExport() {
  // this.download('system/user/export', {
  //     ...this.queryParams
  // }, `用户信息_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  // this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true;
}

// 文件上传成功处理
function handleFileSuccess(response, file, fileList) {
  upload.open = false;
  upload.isUploading = false;
  // $refs.upload.clearFiles();
  // $alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}

function refreshCacheUserFun() {
  refreshCacheUser().then((res: any) => {
    ElMessage.success(res.msg);
  });
}

// 提交上传文件
function submitFileForm() {
  // this.$refs.upload.submit();
}

function nickNameBlueFun() {
  let nickName = form.value.nickName;
  if (nickName) {
    // 转小写
    form.value.userName = firstLetterResult(nickName).toLowerCase();
  } else {
    form.value.userName = "";
  }
}
</script>

<script lang="ts">
export default {
  name: "User"
}
</script>

<style scoped></style>
